<template>
  <div class="alarm-management">
    <!-- 顶部统计卡片 -->
    <div id="overview" class="alarm-stats">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card danger">
            <div class="stats-content">
              <el-icon class="stats-icon"><WarningFilled /></el-icon>
              <div class="stats-info">
                <div class="stats-number">{{ stats.unprocessed }}</div>
                <div class="stats-label">未处理告警</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card warning">
            <div class="stats-content">
              <el-icon class="stats-icon"><Loading /></el-icon>
              <div class="stats-info">
                <div class="stats-number">{{ stats.processing }}</div>
                <div class="stats-label">处理中告警</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card success">
            <div class="stats-content">
              <el-icon class="stats-icon"><CircleCheckFilled /></el-icon>
              <div class="stats-info">
                <div class="stats-number">{{ stats.resolved }}</div>
                <div class="stats-label">已解决告警</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card info">
            <div class="stats-content">
              <el-icon class="stats-icon"><DataLine /></el-icon>
              <div class="stats-info">
                <div class="stats-number">{{ stats.total }}</div>
                <div class="stats-label">总告警数</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <AlarmCharts />

    <!-- 搜索表单和表格区域 -->
    <div id="management" class="management-section">
      <!-- 搜索表单 -->
      <div class="search-form">
        <el-form :model="searchForm" inline>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="告警级别">
            <el-select
              v-model="searchForm.level"
              placeholder="请选择告警级别"
              clearable
              style="width: 160px"
            >
              <el-option
                v-for="option in levelOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="处理状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择处理状态"
              clearable
              style="width: 160px"
            >
              <el-option
                v-for="option in statusOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="告警类型">
            <el-select
              v-model="searchForm.type"
              placeholder="请选择告警类型"
              clearable
              style="width: 180px"
            >
              <el-option
                v-for="option in typeOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="关键字">
            <el-input
              v-model="searchForm.keyword"
              placeholder="告警ID/IP/域名/描述"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 告警表格 -->
      <div class="alarm-table">
        <el-table
          :data="currentTableData"
          style="width: 100%"
          @row-click="handleRowClick"
          v-loading="loading"
        >
          <el-table-column prop="alarmId" label="告警ID" width="150" />
          <el-table-column prop="timestamp" label="告警时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.timestamp) }}
            </template>
          </el-table-column>
          <el-table-column prop="level" label="告警级别" width="100">
            <template #default="scope">
              <el-tag :type="getLevelType(scope.row.level)">
                {{ scope.row.level }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="告警类型" width="150" />
          <el-table-column prop="sourceIp" label="源IP" width="150" />
          <el-table-column prop="targetDomain" label="目标域名" min-width="200">
            <template #default="scope">
              <el-tooltip
                :content="scope.row.targetDomain"
                placement="top"
                :hide-after="0"
              >
                <span class="truncate-text">{{ scope.row.targetDomain }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="处理状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click.stop="handleDetail(scope.row)"
              >
                详情
              </el-button>
              <el-button
                link
                type="primary"
                @click.stop="handleProcess(scope.row)"
              >
                处理
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 告警详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="告警详情"
      width="50%"
      destroy-on-close
    >
      <div class="alarm-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="告警ID">
            {{ currentAlarm.alarmId }}
          </el-descriptions-item>
          <el-descriptions-item label="告警时间">
            {{ formatDate(currentAlarm.timestamp) }}
          </el-descriptions-item>
          <el-descriptions-item label="告警级别">
            <el-tag :type="getLevelType(currentAlarm.level)">
              {{ currentAlarm.level }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="处理状态">
            <el-tag :type="getStatusType(currentAlarm.status)">
              {{ currentAlarm.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="告警类型">
            {{ currentAlarm.type }}
          </el-descriptions-item>
          <el-descriptions-item label="源IP">
            {{ currentAlarm.sourceIp }}
          </el-descriptions-item>
          <el-descriptions-item label="目标域名">
            {{ currentAlarm.targetDomain }}
          </el-descriptions-item>
          <el-descriptions-item label="告警描述" :span="2">
            {{ currentAlarm.description }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleDetailProcess" v-if="currentAlarm.status === '未处理'">
            开始处理
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import dayjs from 'dayjs'
import AlarmCharts from './AlarmCharts.vue'
import { getAlarms, getAlarmStats, updateAlarmStatus } from '../api/alarm'
import type { AlarmData, AlarmStats, AlarmSearchParams, AlarmType } from '../types/alarm'
import { ALARM_TYPES } from '../types/alarm'

// 统计数据
const stats = reactive<AlarmStats>({
  unprocessed: 0,
  processing: 0,
  resolved: 0,
  total: 0
})

// 搜索表单
const searchForm = reactive<AlarmSearchParams>({
  dateRange: undefined,
  level: undefined,
  status: undefined,
  type: undefined,
  keyword: undefined,
  page: 1,
  pageSize: 10
})

// 告警级别选项
const levelOptions = [
  { label: '高危', value: '高危' },
  { label: '中危', value: '中危' },
  { label: '低危', value: '低危' }
]

// 处理状态选项
const statusOptions = [
  { label: '未处理', value: '未处理' },
  { label: '处理中', value: '处理中' },
  { label: '已解决', value: '已解决' }
]

// 告警类型选项
const typeOptions = Object.entries(ALARM_TYPES).map(([_, value]) => ({
  label: value,
  value: value
}))

// 表格数据
const loading = ref(false)
const tableData = ref<AlarmData[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 详情弹窗
const detailVisible = ref(false)
const currentAlarm = reactive<AlarmData>({
  alarmId: '',
  timestamp: '',
  level: '高危',
  sourceIp: '',
  targetDomain: '',
  status: '未处理',
  type: ALARM_TYPES.DGA as AlarmType,
  description: ''
})

// 格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 获取告警级别对应的类型
const getLevelType = (level: string) => {
  const types: Record<string, string> = {
    '高危': 'danger',
    '中危': 'warning',
    '低危': 'info'
  }
  return types[level] || ''
}

// 获取状态对应的类型
const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    '未处理': 'danger',
    '处理中': 'warning',
    '已解决': 'success'
  }
  return types[status] || ''
}

// 加载统计数据
const loadStats = async () => {
  try {
    const data = await getAlarmStats()
    Object.assign(stats, data)
  } catch (error) {
    console.error('Failed to load stats:', error)
  }
}

// 加载表格数据
const loadTableData = async () => {
  loading.value = true
  try {
    const params: AlarmSearchParams = {
      ...searchForm,
      page: currentPage.value,
      pageSize: pageSize.value
    }
    
    if (params.dateRange?.length === 2) {
      const [start, end] = params.dateRange
      params.dateRange = [
        dayjs(start).startOf('day').format('YYYY-MM-DD HH:mm:ss'),
        dayjs(end).endOf('day').format('YYYY-MM-DD HH:mm:ss')
      ]
    }

    const { items, total: totalCount } = await getAlarms(params)
    tableData.value = items
    total.value = totalCount
  } catch (error) {
    console.error('Failed to load alarms:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadTableData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.dateRange = undefined
  searchForm.level = undefined
  searchForm.status = undefined
  searchForm.type = undefined
  searchForm.keyword = undefined
  currentPage.value = 1
  loadTableData()
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadTableData()
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadTableData()
}

// 处理行点击
const handleRowClick = (row: AlarmData) => {
  Object.assign(currentAlarm, row)
  detailVisible.value = true
}

// 处理详情
const handleDetail = (row: AlarmData) => {
  Object.assign(currentAlarm, row)
  detailVisible.value = true
}

// 处理告警处理
const handleProcess = async (row: AlarmData) => {
  try {
    await updateAlarmStatus(row.alarmId, '处理中')
    row.status = '处理中'
    await loadStats()
  } catch (error) {
    console.error('Failed to process alarm:', error)
  }
}

// 从详情弹窗处理告警
const handleDetailProcess = async () => {
  try {
    await updateAlarmStatus(currentAlarm.alarmId, '处理中')
    currentAlarm.status = '处理中'
    await loadStats()
    detailVisible.value = false
    loadTableData()
  } catch (error) {
    console.error('Failed to process alarm:', error)
  }
}

// 当前页数据的计算属性
const currentTableData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return tableData.value.slice(start, end)
})

// 添加锚点定位功能
const scrollToSection = (sectionId: string) => {
  const element = document.getElementById(sectionId)
  if (element) {
    element.scrollIntoView({ behavior: 'smooth' })
  }
}

onMounted(() => {
  // 根据路由 hash 进行定位
  const hash = window.location.hash.slice(1)
  if (hash) {
    setTimeout(() => {
      scrollToSection(hash)
    }, 300)
  }
  loadStats()
  loadTableData()
})
</script>

<style scoped lang="scss">
.alarm-management {
  padding: 24px;
  width: 100%;

  &::-webkit-scrollbar {
    width: 8px;
  }

  &::-webkit-scrollbar-thumb {
    background: #dcdfe6;
    border-radius: 4px;

    &:hover {
      background: #c0c4cc;
    }
  }

  .alarm-stats {
    margin-bottom: 24px;

    .stats-card {
      height: 100%;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-5px);
      }

      .stats-content {
        display: flex;
        align-items: center;
        padding: 20px;
        
        .stats-icon {
          font-size: 48px;
          margin-right: 20px;
          transition: transform 0.3s;
        }

        .stats-info {
          .stats-number {
            font-size: 28px;
            font-weight: bold;
            margin-bottom: 8px;
          }

          .stats-label {
            color: #666;
            font-size: 14px;
          }
        }
      }

      &.danger {
        .stats-icon { color: var(--el-color-danger); }
        .stats-number { color: var(--el-color-danger); }
      }

      &.warning {
        .stats-icon { color: var(--el-color-warning); }
        .stats-number { color: var(--el-color-warning); }
      }

      &.success {
        .stats-icon { color: var(--el-color-success); }
        .stats-number { color: var(--el-color-success); }
      }

      &.info {
        .stats-icon { color: var(--el-color-info); }
        .stats-number { color: var(--el-color-info); }
      }

      &:hover {
        .stats-icon {
          transform: scale(1.1);
        }
      }
    }
  }

  .search-form {
    margin-bottom: 24px;
    padding: 24px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    :deep(.el-form-item) {
      margin-bottom: 18px;
      margin-right: 18px;
    }

    :deep(.el-select) {
      width: 100%;
    }

    :deep(.el-input__wrapper) {
      width: 100%;
    }
  }

  .alarm-table {
    background-color: #fff;
    padding: 24px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    overflow-x: auto;

    .el-table {
      margin-bottom: 16px;

      :deep(th) {
        background-color: #f5f7fa;
        color: #606266;
        font-weight: 600;
      }

      :deep(.el-table__row) {
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          background-color: #f5f7fa;
        }
      }
    }

    .truncate-text {
      display: inline-block;
      max-width: 200px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .pagination {
    margin-top: 24px;
    display: flex;
    justify-content: flex-end;
  }

  .management-section {
    scroll-margin-top: 80px; // 添加滚动偏移，避免被顶部导航栏遮挡
  }
}

.alarm-detail {
  max-height: 70vh;
  overflow-y: auto;
  padding: 16px;

  :deep(.el-descriptions) {
    margin-bottom: 24px;
  }

  :deep(.el-descriptions__title) {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 16px;
  }

  :deep(.el-descriptions__label) {
    width: 120px;
    color: #606266;
  }
}

:deep(.el-dialog__body) {
  padding: 0;
}
</style> 